import axios from 'axios'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor 请求拦截器
service.interceptors.request.use(
  (config) => {
    // console.log('请求拦截器', config)
    const token = store.getters.token
    // console.log(token)
    if (token && !config.noToken) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

import Message from 'element-ui'
// response interceptor 响应拦截器
service.interceptors.response.use(
  (response) => {
    // console.log('响应拦截器', response)
    if (response.status === 200) {
      return response.data
    } else {
      Message.error('请求错误')
      return Promise.reject(new Error('请求错误'))
    }
  }, (error) => {
    // console.log(error.status)
    Message.error(error)
    return Promise.reject(new Error(error))
  }
)

export default service
